# -*- coding: utf-8 -*-
# Created by huangqiyin on 2017/2/18
from pymongo import MongoClient

from settings import config

__all__ = ['init_db', 'get_gameplaza_db', 'get_voice_db', 'get_wxdesk_db', 'get_activity_collection']

config_client = None
_configdb = None


def init_db():
    global config_client
    global _configdb
    config_client = MongoClient(config['CONFIGDB_URL'])
    _configdb = config_client.get_database("config")  # C端用户


def close_db():
    if config_client:
        config_client.close()


def get_user_collection():
    return _configdb.get_collection("user")


def get_usergroup_collection():
    return _configdb.get_collection("usergroup")


def get_env_config_collection():
    return _configdb.get_collection("env_config")


def get_resource_config_collection():
    return _configdb.get_collection("resource_config")


def get_app_config_collection():
    return _configdb.get_collection("app_config")


def get_salt_run_history_collection():
    return _configdb.get_collection("salt_run_history")

def get_global_template_collection():
    return _configdb.get_collection("gobal_template")


def get_history_env_config_collection():
    return _configdb.get_collection("history_env_config")


def get_history_app_config_collection():
    return _configdb.get_collection("history_app_config")


def get_history_global_template_collection():
    return _configdb.get_collection("history_gobal_template")


def get_col_by_name(col_name):
    return _configdb.get_collection(col_name)


def generate_update_info(prefix, conent):
    """
    :brief 生成更新信息, 主要是用于操作mongodb update 指定的字段 包含embedded doc的字段 需要配合$set使用
    :param prefix:
    :param conent:
    :return:
    """
    if not isinstance(conent, dict):
        return {}
    info = {}
    for k, v in conent.items():
        if prefix:
            key = "%s.%s" % (prefix, k)
        else:
            key = k
        if isinstance(v, dict):
            embedded_info = generate_update_info(key, v)
            info.update(embedded_info)
            continue
        info[key] = v
    return info
